const fs = require('fs');
const compressing = require('compressing');
const pipe = require('multipipe');
const path = require('path');

const resolve = (pathUrl) => {
	return path.resolve(__dirname, pathUrl);
};
const gzipPkg = () => {
	let withAssets = false;
	// let assetsFilePath = []
	try {
		fs.accessSync('pkgDist/assets', fs.constants.R_OK | fs.constants.W_OK);
		console.log('CIF.CP.buildPkg:exec 发现静态资源');
		withAssets = true;
		// assetsFilePath = fs.readdirSync("builtPkg/img");
	} catch (err) {
		console.log('CIF.CP.buildPkg:exec 未发现静态资源');
	}

	//把data对象转换为json格式字符串
	const content = JSON.stringify({
		name: pkgConfig.name,
		version: pkgConfig.version,
		type: pkgConfig.type,
		withAssets: withAssets
	});
	//指定创建目录及文件名称，__dirname为执行当前js文件的目录 ../../../builtPkg/baseinfo.json
	const file = resolve('../pkgDist/baseinfo.json');

	//写入文件
	fs.writeFile(file, content, 'utf-8', function (err) {
		if (err) {
			console.log('CIF.CP.buildPkg:exec 配置文件创建失败 ', err);
		}
		console.log('CIF.CP.buildPkg:exec 配置文件创建成功，地址：', file);

		// 检查文件是否存在于当前目录中。
		fs.access(file, fs.constants.F_OK, (err) => {
			console.log(`${file} ${err ? '不存在' : '存在'}`);
		});

		const tarStream = new compressing.zip.Stream();
		// file
		tarStream.addEntry(`../pkgDist/${pkg}.css`);
		tarStream.addEntry(`../pkgDist/${pkg}.umd.js`);
		tarStream.addEntry('../pkgDist/baseinfo.json');

		if (withAssets) {
			tarStream.addEntry('../pkgDist/assets');
		}

		const destStream = fs.createWriteStream(`../pkgDist/${pkg}.zip`);
		pipe(tarStream, destStream, (err) => {
			if (err) console.log(err);
		});
	});
};

module.exports = gzipPkg;
